package cordova.plugin.bugly;

import org.apache.commons.io.input.ReversedLinesFileReader;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;


public class FileUtil {
    public static List<String> getLatestLog(File logFile, int lineNum) throws IOException {
        List<String> lines = new ArrayList<>(lineNum);
        ReversedLinesFileReader reader = null;
        try {
            reader = new ReversedLinesFileReader(logFile, Charset.defaultCharset());
            String current;
            while ((current = reader.readLine()) != null && lines.size() < lineNum) {
                lines.add(0, current);
            }
            return lines;
        } finally {
            if (reader != null) {
                reader.close();
            }
        }
    }

    public static String getLatestLogText(File logFile, int lineNum) throws IOException {
        StringBuffer sb = new StringBuffer();
        for (String line : getLatestLog(logFile, lineNum)) {
            sb.append(line);
            sb.append("\n");
        }
        return sb.toString();
    }
}